#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>

#define MAX 10

typedef void (*fun)();
fun prog[MAX] = {NULL}; //函数指针数组

void WriteData()
{
    printf("正在写入数据!\n");
}

void ReadData()
{
    printf("正在读取数据!\n");
}

void UploadData()
{
    printf("正在上传数据!\n");
}

void InsertTask(fun f)
{
    if(prog[MAX-1]!=NULL)
    {
        for(int i = 0;i<MAX-1;++i)
        {
            prog[i] = prog[i+1];
        }
        prog[MAX-1] = f;
    }
    else
    {
        for(int i = 0;i<MAX;++i)
        {
            if(prog[i] != NULL) continue;
            prog[i] = f;
            break;
        }
    }
}

void InitTask()
{
    for(int i = 0;i<MAX;++i)
    {
        prog[i] = NULL;
    }
    InsertTask(ReadData);
    InsertTask(WriteData);
    InsertTask(UploadData);
}

void RunProg()
{
    for(int i = 0;i<MAX&&prog[i];++i)
    {
        prog[i]();
    }
}

int main()
{
    pid_t ret = fork();
    if(ret == 0)
    {
        //制造错误异常退出
        //int* ptr = NULL;
        //*ptr = 1;
        for(int i = 0;i<5;++i)
        {
            printf("子进程运行中!pid:%d ppid:%d\n",getpid(),getppid());
            sleep(1);
        }
        exit(-1);//控制子进程退出码
    }
    InitTask();
    while(1)
    {
        int status = 0;
        ret = waitpid(ret,&status,WNOHANG);
        if(ret < 0)
        {
            printf("waitpid error!\n");
            exit(9);
        }
        else if(ret == 0)
        {
            RunProg();//父进程等待子进程时做一些其他事情
            sleep(1);
            continue;
        }
        else if(ret > 0)
        {
            if(WIFEXITED(status))
            {
                printf("\n正常退出>子进程pid:%d 退出码:%d 终止信号%d\n\n",ret,WEXITSTATUS(status),status&0x7F);
            }
            else
            {
                printf("\n异常退出>子进程pid:%d 退出码:%d 终止信号%d\n\n",ret,WEXITSTATUS(status),status&0x7F);
            }
            break;
        }

    }


}